//
//  FYFMessageToolbar.m
//  
//
//  Created by fuyoufang on 15/10/19.
//
//

#import "FYFMessageToolbar.h"

@implementation FYFMessageToolbar

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

#import "DXMessageToolBar.h"
#import "ESToolbarView.h"

@interface DXMessageToolBar()<ESFacialInputViewDelegate, ESToolbarViewDelegate>
/** 整体背景 */
@property (strong, nonatomic) UIImageView *backgroundImageView;

/** toolbarView */
@property (weak, nonatomic) ESToolbarView *toolbarView;
/** toolbarView 高度约束 */
@property (weak, nonatomic) NSLayoutConstraint *toolbarViewHeight;
/** 底部扩展页面 */
@property (nonatomic) BOOL isShowButtomView;
/** 当前活跃的底部扩展页面  */
@property (weak, nonatomic) UIView *activityButtomView;

/** 更多的附加页面 */
@property (strong, nonatomic) DXChatBarMoreView *moreView;
/** 表情的附加页面 */
@property (strong, nonatomic) ESFacialInputView *faceView;

#warning TODO 这个属性不应该放在这里
/** 录音的附加页面 */
@property (strong, nonatomic) UIView *recordView;

@end

@implementation DXMessageToolBar
#pragma mark - getter
- (DXChatBarMoreView *)moreView {
    if (_moreView == nil) {
#warning TODO type
        _moreView = [[DXChatBarMoreView alloc] initWithFrame:CGRectZero type:ChatMoreTypeChat];
        _moreView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:_moreView];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[moreView]|" options:NSLayoutAttributeLeading | NSLayoutAttributeTrailing metrics:nil views:@{@"moreView" : _moreView}]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[moreView(moreViewHeight)]|" options:NSLayoutAttributeLeading | NSLayoutAttributeTrailing metrics:@{@"moreViewHeight" : @(_moreView.frameHeight)} views:@{@"moreView" : _moreView}]];
    }
    return _moreView;
}

- (ESFacialInputView *)faceView {
    if (_faceView == nil) {
        _faceView = [[ESFacialInputView alloc] initWithTextView:self.toolbarView.messageTextView];
        _faceView.delegate = self;
        _faceView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:_faceView];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[faceView]|" options:NSLayoutAttributeLeading | NSLayoutAttributeTrailing metrics:nil views:@{@"faceView" : _faceView}]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[faceView(faceViewHeight)]|" options:NSLayoutAttributeLeading | NSLayoutAttributeTrailing metrics:@{@"faceViewHeight" : @(_faceView.frameHeight)} views:@{@"faceView" : _faceView}]];
    }
    return _faceView;
}

- (UIImageView *)backgroundImageView {
    if (_backgroundImageView == nil) {
        _backgroundImageView = [[UIImageView alloc] init];
        _backgroundImageView.backgroundColor = [UIColor clearColor];
        _backgroundImageView.translatesAutoresizingMaskIntoConstraints = NO;
#warning TODO topCapHeight == 10 ？？
        _backgroundImageView.image = [[UIImage imageNamed:@"messageToolbarBg"] stretchableImageWithLeftCapWidth:0.5 topCapHeight:10];
    }
    
    return _backgroundImageView;
}


#pragma mark - 系统方法
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupConfigure];
        [self setupSubviews];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}


#pragma mark - UIKeyboardNotification
- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect beginFrame = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    [UIView animateWithDuration:duration delay:0.0f options:(curve << 16 | UIViewAnimationOptionBeginFromCurrentState) animations:^{
        [self willShowKeyboardFromFrame:beginFrame toFrame:endFrame];
    } completion:nil];
}

#pragma mark - private

/**
 *  设置初始属性
 */
- (void)setupConfigure {
    self.activityButtomView = nil;
    self.isShowButtomView = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

/**
 *  设置设置子 view
 */
- (void)setupSubviews {
    // toolbarView
    ESToolbarView *toolbarView = [ESToolbarView toolbarView];
    toolbarView.delegate = self;
    toolbarView.translatesAutoresizingMaskIntoConstraints = NO;
    [self addSubview:toolbarView];
    self.toolbarView = toolbarView;
    NSLayoutConstraint *toolbarViewHeight = [NSLayoutConstraint constraintWithItem:toolbarView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:[ESToolbarView defaultHeight]];
    [self.toolbarView addConstraint:toolbarViewHeight];
    self.toolbarViewHeight = toolbarViewHeight;
    
    [self addConstraint:[NSLayoutConstraint constraintWithItem:toolbarView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(0)-[toolbarView]-(0)-|" options:NSLayoutAttributeLeading | NSLayoutAttributeTrailing metrics:nil views:@{@"toolbarView": toolbarView}]];
    
    [self addSubview:self.backgroundImageView];
    
#warning TODO 设置其他几个 view
}

#pragma mark - change frame
/**
 *  改变底部距离 superView 的距离
 */
- (void)willShowBottomHeight:(CGFloat)bottomHeight {
    if (bottomHeight == 0) {
        self.isShowButtomView = NO;
    } else {
        self.isShowButtomView = YES;
    }
    
    if ([self.delegate respondsToSelector:@selector(messageToolbar:shouldChangeFrameToBottom:)]) {
        [self.delegate messageToolbar:self shouldChangeFrameToBottom:bottomHeight];
    }
}


/**
 * 键盘 frame 改变
 */
- (void)willShowKeyboardFromFrame:(CGRect)beginFrame toFrame:(CGRect)toFrame {
    if (beginFrame.origin.y == [[UIScreen mainScreen] bounds].size.height) { // 键盘弹出
        // 一定要把self.activityButtomView置为空
        if (self.activityButtomView) {
            [self.activityButtomView removeFromSuperview];
        }
        self.activityButtomView = nil;
        [self willShowBottomHeight:toFrame.size.height];
    } else if (toFrame.origin.y == [[UIScreen mainScreen] bounds].size.height) { // 键盘收回
        [self willShowBottomHeight:0];
    } else {
        [self willShowBottomHeight:toFrame.size.height];
    }
}

#pragma mark - public

/**
 *  停止编辑
 */
- (BOOL)endEditing:(BOOL)force {
    [self willShowBottomHeight:0];
    if (self.faceView) {
        [self.faceView removeFromSuperview];
        self.faceView = nil;
    }
    if (self.moreView) {
        [self.moreView removeFromSuperview];
        self.moreView = nil;
    }
    if ([self.delegate respondsToSelector:@selector(messageToolbar:shouldChangeFrameToHeight:)]) {
        [self.delegate messageToolbar:self shouldChangeFrameToHeight:self.toolbarViewHeight.constant];
    }
    return [self.toolbarView endEditing:force] &&[super endEditing:force];
}

/**
 *  取消触摸录音键
 */
- (void)cancelTouchRecord {
    //    self.recordButton.selected = NO;
    //    self.recordButton.highlighted = NO;
    if ([_recordView isKindOfClass:[DXRecordView class]]) {
        [(DXRecordView *)_recordView recordButtonTouchUpInside];
        [_recordView removeFromSuperview];
    }
}

+ (CGFloat)defaultHeight {
    return kVerticalPadding * 2 + kInputTextViewMinHeight;
}



#pragma mark - DXFaceDelegate
#warning TODO 暂时注释
//- (void)selectedFacialView:(NSString *)str isDelete:(BOOL)isDelete {
//    NSString *chatText = self.inputTextView.text;
//
//    if (!isDelete && str.length > 0) {
//        self.inputTextView.text = [NSString stringWithFormat:@"%@%@",chatText,str];
//    }
//    else {
//        if (chatText.length >= 2) {
//            NSString *subStr = [chatText substringFromIndex:chatText.length-2];
//            if ([(ESFacialInputView *)self.faceView stringIsFace:subStr]) {
//                self.inputTextView.text = [chatText substringToIndex:chatText.length-2];
//                [self textViewDidChange:self.inputTextView];
//                return;
//            }
//        }
//
//        if (chatText.length > 0) {
//            self.inputTextView.text = [chatText substringToIndex:chatText.length-1];
//        }
//    }
//
//    [self textViewDidChange:self.inputTextView];
//}
//
//- (void)sendFace {
//    NSString *chatText = self.inputTextView.text;
//    if (chatText.length > 0) {
//        if ([self.delegate respondsToSelector:@selector(didSendText:)]) {
//            [self.delegate didSendText:chatText];
//            self.inputTextView.text = @"";
//            [self willShowInputTextViewToHeight:[self getTextViewContentH:self.inputTextView]];;
//        }
//    }
//}

#pragma mark - ESToolbarViewDelegate
#pragma mark 录音按钮
/** 按下录音按钮开始录音 */
- (void)didStartRecordingVoiceAction:(ESToolbarView *)toolbarView {
    
}

/** 手指向上滑动取消录音 */
- (void)didCancelRecordingVoiceAction:(ESToolbarView *)toolbarView {
    
}

/** 松开手指完成录音 */
- (void)didFinishRecoingVoiceAction:(ESToolbarView *)toolbarView {
    
}

/** 当手指离开按钮的范围内时，主要为了通知外部的HUD */
- (void)didDragOutsideAction:(ESToolbarView *)toolbarView {
    
}

/** 当手指再次进入按钮的范围内时，主要也是为了通知外部的HUD */
- (void)didDragInsideAction:(ESToolbarView *)toolbarView {
    
}

#pragma mark style
- (void)toolbarView:(ESToolbarView *)toolbarView didChangedMessageInputStyle:(MessageInputStyle)style {
    if (style == MessageInputStyleKeyboard
        || style == MessageInputStyleRecord) {
        if ([self.delegate respondsToSelector:@selector(messageToolbar:shouldChangeFrameToHeight:)]) {
            [self.delegate messageToolbar:self shouldChangeFrameToHeight:self.toolbarViewHeight.constant];
        }
        if (self.faceView) {
            [self.faceView removeFromSuperview];
            self.faceView = nil;
        }
        if (self.moreView) {
            [self.moreView removeFromSuperview];
            self.moreView = nil;
        }
    } else if (style == MessageInputStyleMore) {
        if ([self.delegate respondsToSelector:@selector(messageToolbar:shouldChangeFrameToHeight:)]) {
            [self.delegate messageToolbar:self shouldChangeFrameToHeight:(self.moreView.frameHeight + self.toolbarViewHeight.constant)];
        }
        self.activityButtomView = self.moreView;
        if (self.faceView) {
            [self.faceView removeFromSuperview];
            self.faceView = nil;
        }
    } else if (style == MessageInputStyleFacial) {
        if ([self.delegate respondsToSelector:@selector(messageToolbar:shouldChangeFrameToHeight:)]) {
            [self.delegate messageToolbar:self shouldChangeFrameToHeight:(self.faceView.frameHeight + self.toolbarViewHeight.constant)];
        }
        self.activityButtomView = self.faceView;
        if (self.moreView) {
            [self.moreView removeFromSuperview];
            self.moreView = nil;
        }
    }
}

#pragma mark inputTextView
- (void)toolbarView:(ESToolbarView *)toolbarView inputTextViewWillBeginEditing:(UITextView *)textField {
    if ([self.delegate respondsToSelector:@selector(messageToolBar:inputTextViewWillBeginEditing:)]) {
        [self.delegate messageToolBar:self inputTextViewWillBeginEditing:textField];
    }
    // 一定要把self.activityButtomView置为空
    [self.moreView removeFromSuperview];
    [self.faceView removeFromSuperview];
    [self willShowBottomHeight:self.toolbarViewHeight.constant];
    if ([self.delegate respondsToSelector:@selector(messageToolbar:shouldChangeFrameToHeight:)]) {
        [self.delegate messageToolbar:self shouldChangeFrameToHeight:self.toolbarViewHeight.constant];
    }
}

- (void)toolbarView:(ESToolbarView *)toolbarView inputTextViewDidBeginEditing:(UITextView *)textField {
    if ([self.delegate respondsToSelector:@selector(messageToolBar:inputTextViewDidBeginEditing:)]) {
        [self.delegate messageToolBar:self inputTextViewDidBeginEditing:textField];
    }
}

- (void)toolbarView:(ESToolbarView *)toolbarView inputTextViewDidEnterReturn:(UITextView *)textField {
    
}

- (void)toolbarView:(ESToolbarView *)toolbarView inputTextViewDidEndEditing:(UITextView *)textField {
    if ([self.delegate respondsToSelector:@selector(messageToolbar:shouldChangeFrameToHeight:)]) {
        [self.delegate messageToolbar:self shouldChangeFrameToHeight:self.toolbarViewHeight.constant];
    }
}
#pragma mark 高度
- (void)toolbarView:(ESToolbarView *)toolbarView needChangeToHeight:(CGFloat)height {
#warning TODO 改变 toolbarView 和自身的高度
    //    CGRect rect = self.frame;
    //    rect.size.height += changeHeight;
    //    rect.origin.y -= changeHeight;
    //    self.frame = rect;
    //
    //    rect = self.toolbarView.frame;
    //    rect.size.height += changeHeight;
    //    self.toolbarView.frame = rect;
}



@end

